package com.example.baijiebrower.update;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import androidx.core.content.FileProvider;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @ClassName UpdateJson
 * @Author liufeng
 * @Date 2024/9/11
 * @email liufeng@szbaijie.cn
 * @Description
 */
public class UpdateJson {

    private int id;
    private String url = "http://down.szbaijie.com:8088/helperboard/baijieERP/index/index.html";
    private String name;
    private String publishTime;
    private String versionName;
    private String updateMessage;
    private String downloadUrl;
    private int versionCode;
    private boolean success;
    public static JSONObject jSONObject = null;
    private HttpURLConnection connection;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getPublishTime() {
        return publishTime;
    }

    public String getVersionName() {
        return versionName;
    }

    public String getUpdateMessage() {
        return updateMessage;
    }

    public String getDownloadUrl() {
        return downloadUrl;
    }

    public boolean getSuccess() {
        return success;
    }

    public int getVersionCode() {
        return versionCode;
    }


    //检查更新链接是否有效的方法
    public boolean checkUrl(String url) {
        try {
            URL infoUrl = new URL(url);
            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public  JSONObject jsonToNetwork() {
        URL infoUrl;
        InputStream inStream;
        String line;
        try {
            boolean isConnect = checkUrl(url);
            if (isConnect){
                infoUrl = new URL(url);
                URLConnection connection = infoUrl.openConnection();
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                int responseCode = httpConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    inStream = httpConnection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
                    StringBuilder strber = new StringBuilder();
                    while ((line = reader.readLine()) != null){
                        strber.append(line + "\n");}
                    inStream.close();
                    int start = strber.indexOf("{");
                    int end = strber.indexOf("}");
                    String json = strber.substring(start, end + 1);
                    Log.d("Json", "jsonToNetwork: "+json);
                    if (json != null) {
                        try {
                            jSONObject = new JSONObject(json);
                            id = jSONObject.getInt("id");
                            publishTime = jSONObject.getString("publishTime");
                            name = jSONObject.getString("name");
                            versionName = jSONObject.getString("versionName");
                            versionCode = jSONObject.getInt("versionCode");
                            updateMessage = jSONObject.getString("updateMessage");
                            downloadUrl = jSONObject.getString("downloadUrl");
                            success = jSONObject.getBoolean("success");
                            return jSONObject;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public File downloadFile(Context context ,String downloadUrl , NumberProgressBar numberProgressBar) throws Exception {
        int total_length = 0;
        BufferedOutputStream outStream = null;
        BufferedInputStream inputStream = null;
        URL url = new URL(downloadUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        //connection.setRequestProperty("Accept-Encoding", "identity");
        connection.connect();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
            InputStream is = connection.getInputStream();
            inputStream = new BufferedInputStream(is);
            //File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File downloadDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
            File file = new File(downloadDir, "baiJieERP.apk");
            if (!file.exists()){
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(file);
            outStream = new BufferedOutputStream(out);
            byte[] byteArray = new byte[1024 * 8];
            int len;
            long fileLength = connection.getContentLength();
            while ((len = inputStream.read(byteArray)) != -1){
                outStream.write(byteArray, 0, len);
                total_length += len;
                if (numberProgressBar != null && fileLength > 0){
                    numberProgressBar.setProgress((int) ((total_length / (float) fileLength) * 100));
                }
            }
            if (inputStream != null){
                inputStream.close();
            }
            if (outStream != null){
                outStream.close();
            }
            return file;
        }
        return null;
    }

    public void installApk( Context context , File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public boolean compareVersionsName(String version1, String version2) {
        if (version1 != null || version2 != null){
            String[] parts1 = version1.split("\\.");
            String[] parts2 = version2.split("\\.");
            String[] parts3 = version1.split("\\.");

            int i = 0;
            while (i < parts1.length || i < parts2.length || i < parts3.length) {
                int num1 = i < parts1.length ? Integer.parseInt(parts1[i]) : 0;
                int num2 = i < parts2.length ? Integer.parseInt(parts2[i]) : 0;
                int num3 = i < parts3.length ? Integer.parseInt(parts3[i]) : 0;

                // 比较数字
                if (num1 > num2) {
                    return true;
                } else if (num2 > num3) {
                    return true;
                }

                i++;
            }
            return false;
        }else {
            return false;
        }
    }

}
